package com.apes.scm.pur.purchaseReturn.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Map;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PurchaseReturnItem.CONST_TABLE_NAME,indexes = {
        @Index(name = "idx_return_id", columnList = "return_id"),
        @Index(name = "idx_return_product_id", columnList = "product_id")
       }
)
public class PurchaseReturnItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "pur_purchase_return_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "返厂订单明细")
    @Comment("唯一编码")
    private long id;
    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "return_id", referencedColumnName = "id")
    @Comment("返厂订单号")
    private PurchaseReturn purchaseReturn;

    @Column(name = "voucher_Origin", length = 30)
    @Comment("凭证源单据")
    private String voucherOrigin;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id")
    @Comment("商品")
    private Product product;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "barch_code",referencedColumnName = "id")
    @Comment("商品批次内码")
    private InventoryBatch inventoryBatch;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id")
    @Comment("计量单位")
    private ProductUom uom;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id")
    @Comment("税率")
    private Tax tax; //税率

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("小计（未含税金额）")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    @Column(name = "product_sum_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("商品总数（可退数量）")
    private double productSumQty = 0;

    @Column(name = "product_return_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("返厂数量")
    private double productReturnQty = 0;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已发货数量")
    private double qtyReceived = 0;

    @Column(name = "cancel_qty", columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("终止数量")
    private double cancelQty = 0;


    public void computeAmt() {
        Map result = this.getTax().computeAll(this.purchaseReturn.getCompany(), priceUnit, productReturnQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
    }


    /*
     * 功能：计算含税库存单价
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /*
     * 功能：计算基本单位库存量
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.purchaseReturn.getCompany(), this.getProduct());
    }

    /**
     * 更新发货数量
     */
    public void delivery(double qtyDone) {
        this.qtyReceived += qtyDone;
        if (qtyReceived > productReturnQty) {
            throw new RuntimeException("接收数量不允许大于订单数量！");
        }
    }

}
